package cn.tonyandmoney.warescanapp.socket

import com.codebutler.android_websockets.WebSocketClient
import io.reactivex.subjects.PublishSubject
import java.lang.Exception
import java.net.ConnectException

/**
 * Created by niantuo on 2018/2/27.
 * webSocket 回调
 * 状态记录
 * 未发送的消息记录
 */
class WebSocketHandler(private val mUrl: String,
                       private val mBus: PublishSubject<RxSocketEvent>) : WebSocketClient.Listener {

    private var isConnect: Boolean = false

    fun isConnecting() = isConnect


    override fun onConnect() {
        isConnect = true
        mBus.onNext(RxSocketEvent(mUrl, RxSocketEvent.CODE_CONNECT))
    }

    override fun onMessage(bytes: ByteArray?) {
        mBus.onNext(RxSocketEvent(mUrl, RxSocketEvent.CODE_MSG_BYTE, data = bytes))
    }

    override fun onMessage(msg: String) {
        mBus.onNext(RxSocketEvent(mUrl, RxSocketEvent.CODE_MSG_STRING, msg))
    }

    override fun onDisconnect(code: Int, reason: String?) {
        isConnect = false
        mBus.onNext(RxSocketEvent(mUrl, RxSocketEvent.CODE_DISCONNECT, reason
                ?: "已断开连接。", errCode = code))
    }

    override fun onError(e: Exception) {
        if (e is ConnectException) {
            mBus.onNext(RxSocketEvent(mUrl, RxSocketEvent.CODE_CONNECT_ERROR, error = e))
        } else {
            mBus.onNext(RxSocketEvent(mUrl, RxSocketEvent.CODE_ERROR_UNKNOWN, error = e))
        }
    }
}